import Config from './config'
import Toast from './toast'

const Target = {
  self: '/',
  intf: '/call/mop-epay-intf'
}

const HttpUtil = {
  ticket: '',
  get: (target, url, data, header, failToast=true) => {
    return HttpUtil.fetch({
      url: url.startsWith('http') ? url : Config.ctx + target + url,
      data: data,
      header: header,
      method: 'GET',
      failToast: failToast
    })
  },
  post: (target, url, data, header, failToast = true) => {
    console.log('ticket = ', HttpUtil.ticket)
    return HttpUtil.fetch({
      url: url.startsWith('http') ? url : Config.ctx + target + url,
      data: data,
      header: header,
      method: 'POST',
      failToast: failToast
    })
  },
  put: (target, url, data, header, failToast = true) => {
    return HttpUtil.fetch({
      url: handleUrlMethod(url.startsWith('http') ? url : Config.ctx + target + url, 'PUT'),
      data: data,
      header: header,
      method: 'POST',
      failToast: failToast
    })
  },
  delete: (target, url, data, header, failToast = true) => {
    return HttpUtil.fetch({
      url: handleUrlMethod(url.startsWith('http') ? url : Config.ctx + target + url, 'DELETE'),
      data: data,
      header: header,
      method: 'POST',
      failToast: failToast
    })
  },
  patch: (target, url, data, header, failToast = true) => {
    return HttpUtil.fetch({
      url: handleUrlMethod(url.startsWith('http') ? url : Config.ctx + target + url, 'PATCH'),
      data: data,
      header: header,
      method: 'POST',
      failToast: failToast
    })
  },
  fetch: (obj) => {
    return new Promise((resolve, reject) => {
      wx.request({
        url: obj.url,
        data: Object.assign(obj.data || {}, {
          // terminal_type: 'PHONE',
          // os_type: 'WX'
        }),
        header: Object.assign({}, {
          'content-type': 'application/json'
          // ticket: '' + HttpUtil.ticket,
          // ret_flag: 'ticket_info'
        }, obj.header),
        method: obj.method || 'GET',
        dataType: 'json',
        success: (res) => {
          Toast.hideLoading()
          if (res.statusCode==203){
            Toast.message(res.data);
            return
          }
          if (res.statusCode >= 400) {
            if (obj.failToast === true && res.statusCode == 500) {
              let message = typeof res.data == 'string' ? res.data : res.data.error 
              if(message.search('<script>') > -1) {
                message = '服务器出现异常，请稍后再试'
              }
              Toast.message(message)
            } 
            else if (res.statusCode == 404) {
              Toast.message('请求的资源不存在')
            }
            //票据失效，跳转登录页面
            if (res.statusCode == 401) {
              wx.reLaunch({
                url: '/pages/index/index'
              })
            }
            reject(res.data)
            return
          }

          if(typeof res.data.code === 'string') {
            if (res.data.code === '0000') {
              resolve(res.data)
            } else {
              if (obj.failToast === true) {
                Toast.message(res.data.msg)
              }
              //票据失效，跳转登录页面
             
              if (res.data.code === '0001' && obj.data.login == undefined) {
                wx.reLaunch({
                  url: '/pages/index/index'
                })
              }
              reject(res.data)
              return
            }
          } else {
            resolve(res.data)
            return
          }
        },
        fail: (res) => {
          Toast.hideLoading()
          if (obj.failToast === true) {
            Toast.message('请求链接失败')
          }
          reject(res)
        }
      })
    })
  },

  /**
   * 坐标转换
   * from 来源坐标系 
   * to 转换后的坐标 百度转GCJ02 5->3 GCJ02转百度 3->5
   */
  convertCoordinate(longitude, latitude, from, to) {
    return new Promise((reslove, reject) => {
      wx.request({
        url: `https://api.map.baidu.com/geoconv/v1/?coords=${longitude},${latitude}&from=${from}&to=${to}&ak=${Config.webbdak}`,
        method: 'GET',
        data: {
          from: from,
          to: to,
          x: longitude,
          y: latitude
        },
        dataType: 'json',
        success: function(res) {
          console.log(res)
          let x = res.data.result[0].x
          let y = res.data.result[0].y
          console.log('转换成功', {
            x: longitude,
            y: latitude,
            x1: x,
            y1: y,
          })
          reslove({
            longitude: x,
            latitude: y,
          })
        },
        fail: function(res) {
          reject()
        }
      })
    })
  }
}

const handleUrlMethod = (url, type) => {
  var methodStr = "_method=" + type;
  if (url.indexOf("?") < 0) {
    url = url + "?" + methodStr;
  } else if (url[url.length - 1] == "?") {
    url += methodStr;
  } else {
    url = url + "&" + methodStr;
  }
  return url
}

const formDataValidate = function (formData, options) {
  var map = {};
  for (let index in options) {
    let item = options[index]
    let value = formData[item.id]
    if(typeof item.func === 'function' && item.func(value)) {
      return `${item.name}格式不正确`
    }
    //文本输入类
    if (['text', 'phone', 'number', 'idcard'].indexOf(item.type) != -1) {
      //先判断是否为空
      if (value == undefined || value == '') {
        if (item.required) {
          return `请输入${item.name}`
          break
        } else {
          continue
        }
      }
      //判断是否符合规则
      if (item.type == 'phone') {
        item.regex = /(^$)|(^400(-?)\d{7}$)|(^1[345789]\d{9}$)/
      }
      else if (item.type == 'number') {
        item.regex = /^\d+(\.\d+)?$/
      }
      else if (item.type == 'idcard') {
        item.regex = /^([1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx])|([1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx])$/
      }
      if (item.regex && !item.regex.test(value)) {
        return `${item.name}格式不正确`
        break
      }
      continue
    }
    //选择类型
    if (['select', 'select-input', 'select-upload'].indexOf(item.type) != -1) {
      if (item.required && (
        value == undefined ||
        value == '' ||
        value == '[]' ||
        (typeof value == 'object' && Object.keys(value).length == 0))) {
        if (item.type == 'select') {
          return `请选择${item.name}`
          break
        }
        if (item.type == 'select-input') {
          return `请填写${item.name}`
          break
        }
        if (item.type == 'select-upload') {
          return `请上传${item.name}`
          break
        }
      }
      continue
    }

    //一个组中的项必填其一
    var groupValue = item.group;
    if (['have-one'].indexOf(item.type) != -1 && Object.keys(map).indexOf(groupValue) > -1) {
      map[groupValue].push(item);
    } else {
        var array = [];
        array.push(item);
        map[groupValue] = array;
    }
    
  }

  for (var key in map) {
    var flag = false;
    var array = map[key];
    for (var item in array) {
      var value = formData[array[item].id];
      if (!((value == undefined ||
        value == '' ||
        value == '[]') ||
        (typeof value == 'object' && Object.keys(value).length == 0))) {
        flag = true;
        break;
      }
      continue;
    }

    if (!flag) {
      return array.reduce((total, item) => total + ',' + item.name, '').substring(1) + '必填其一'
    }
  }
}

module.exports = {
  Config,
  Target,
  HttpUtil,
  Toast,
  formDataValidate,
} 